<!DOCTYPE html>
<html class="ui-page-login">

	<head>
		<meta charset="utf-8">
		<meta name="viewport" content="width=device-width,initial-scale=1,minimum-scale=1,maximum-scale=1,user-scalable=no" />
		<title></title>
		<link href="../../css/mui.min.css" rel="stylesheet" />
		<link href="../../css/style.css" rel="stylesheet" />
		<style>
			body{
				background: #222222;
			}
			.area {
				margin: 20px auto 0px auto;
			}
			.mui-input-group:first-child {
				margin-top: 20px;
			}
			.mui-input-group label {
				width: 22%;
			}
			.mui-input-row label~input,
			.mui-input-row label~select,
			.mui-input-row label~textarea {
				width: 78%;
			}
			.mui-checkbox input[type=checkbox],
			.mui-radio input[type=radio] {
				top: 6px;
			}
			.mui-content-padded {
				margin-top: 25px;
			}
			.mui-btn {
				padding: 10px;
			}
			.container {
				height:60vh;
			}
		</style>
	</head>

	<body>
		<header class="mui-bar mui-bar-nav" style="background-color: #000000; ">
			<a class="mui-action-back mui-icon mui-icon-left-nav mui-pull-left"></a>
			<h1 class="mui-title" style="color: #FFFFFF;">修改个人信息</h1>
		</header>
		<div class="mui-content" style="background-color: #222222;">
		<div class=" container">
		      	<input id='nickname' type="text" class="mui-input-clear mui-input" placeholder="修改昵称">
		      	<input id='account' type="text" class="mui-input-clear mui-input" placeholder="修改账号">
		      	<div><img id="images" class="userImg" style="margin:3vw;width: 10vw;height: 10vw; border-radius: 360px;" src="../../images/nickname.png" />
		         <a class="" style="float: right;margin-right: 10vw;margin-top: 5vw;" id="userImg"  href="#">修改头像</a></div>
		      <button  id='reg'>修改</button>
		  </div>
		</div>
		<script src="../../js/mui.min.js"></script>
		<script src="../../js/app.js"></script>
		<script type="text/javascript" src="../js/common.js"></script>
		<script>
			  
			
			mui.plusReady(function(){
				var mask = mui.createMask(); //遮罩层
			    document.getElementById('userImg').addEventListener('tap',function(){
					
			        if(mui.os.plus){
			            var a=[{
			                title:'拍照'
			            },{
			                title:'从手机相册选择'
			            }];
			            plus.nativeUI.actionSheet({
			                title:'上传头像',
			                cancel:'取消',
			                buttons:a
			            },function(b){
			                switch(b.index){
			                    case 0:
			                        break;
			                    case 1:
			                        //拍照
			                        getImages();
			                        break;
			                    case 2:
			                        //打开相册
			                        galleryImages();
			                        break;
			                    default:
			                        break;
			                }
			            },false);   
			        }
			    });
			
			    //拍照
			    function getImages(){
			        var mobileCamera=plus.camera.getCamera();
			        mobileCamera.captureImage(function(e){
			            plus.io.resolveLocalFileSystemURL(e,function(entry){
			                var path=entry.toLocalURL()+'?version='+new Date().getTime();
			                fileUploader(path)
			            },function(err){
			                console.log("读取拍照文件错误");
			            });
			        },function(e){
			            console.log("er",err);
			        },function(){
			            filename:'_doc/head.png';
			        });
			    }
			
			    //从本地相册选择
			 function galleryImages(){
			plus.gallery.pick(function(path){
				fileUploader(path)
					console.log(path);
					var images=new Image();
					images.src=path;
					console.log("base:"+images.width);
					//showImg( path );
					//createItem(path);
				}, function(e){
				outSet('取消选择图片');
					}, {filter:'image'});
			    };
				var user = app.getUserInfo();
				var imgepath = user.headImageUrl;
				var images = document.getElementById("images");
				images.src = imgepath;
				var nickname = document.getElementById('nickname');
				var accountBox = document.getElementById('account');
				nickname.value = user.nickname;
				accountBox.value = user.username;
				 
			    function fileUploader(filePath){
					var images = document.getElementById("images");
					images.src = filePath;
			            // 获取token 
						plus.nativeUI.showWaiting("上传中，请等待...", "options");
						mask.show();
			    　　　　　　　// token 我上传时需要的参数
			    　　　　　　　// localStorage.upload_url + "api/post/file  要上传的服务器地址
			                let task = plus.uploader.createUpload(app.getUrl()+"userinfo/uploadUserHeadImage", 
			                  { method:"POST",blocksize:204800,priority:100 },
			                  ( t, status ) => {
								  var data = t.responseText
			                    // 上传完成
			                    if(status == 200){
			                      let responseTextJson = JSON.parse(t.responseText);
			                      if(responseTextJson && responseTextJson.errCode == "000000"){
			                          console.log(responseTextJson,'请求成功返回的信息')
										imgepath = responseTextJson.data;
										plus.nativeUI.toast('上传成功...');
										plus.nativeUI.closeWaiting();
										mask.close(); //关闭遮罩层
			                      }else{
			                       console.log("服务错误,请稍后在试!")
			                      }
			                    }else{
			                      console.log(JSON.stringify(t))
			                     　console.log("网络错误,请稍后在试!")
			                    }
			                  }
			                );
			    　　　　　　　//添加上传文件
			    　　　　　　　// filePath 上传文件的路径（仅支持本地文件路径）详情见 http://www.html5plus.org/doc/zh_cn/uploader.html#plus.uploader.Upload.addFile
			     
			                task.addFile(filePath, {key: "file"} );
			                // 开始上传
			                task.start();
			              
			          }
			     
			     
			    　　　
			    　　　function getBase64(img){
			            function getBase64Image(img,width,height) {//width、height调用时传入具体像素值，控制大小 ,不传则默认图像大小
			              var canvas = document.createElement("canvas");
			              canvas.width = width ? width : img.width;
			              canvas.height = height ? height : img.height;
			     
			              var ctx = canvas.getContext("2d");
			              ctx.drawImage(img, 0, 0, canvas.width, canvas.height);
			              var dataURL = canvas.toDataURL();
			              return dataURL;
			            }
			            var image = new Image();
			            image.crossOrigin = '';
			            image.src = img;
			            var deferred=$.Deferred();
			            if(img){
			              image.onload =function (){
			                deferred.resolve(getBase64Image(image));//将base64传给done上传处理
			              }
			              return deferred.promise();//问题要让onload完成后再return sessionStorage['imgTest']
			            }
			          }
			(function($, doc) {
				$.init();
				$.plusReady(function() {
					
					var settings = app.getSettings();
					var regButton = doc.getElementById('reg');
					var nickname = doc.getElementById('nickname');
					var accountBox = doc.getElementById('account');
					regButton.addEventListener('tap', function(event) {
						var user = app.getUserInfo();
						var regInfo = {
							userId:user.userId,
							username:accountBox.value,
							nickname:nickname.value,
							headImageUrl:imgepath,
						};
						if(accountBox.value.toString() == "") {
							mui.toast('请输入账号!', {
								duration: 'long',
								type: 'div'
							}) 
							return false;
						}
						if(nickname.value.toString() == "") {
							mui.toast('请输入昵称!', {
								duration: 'long',
								type: 'div'
							}) 
							return false;
						}
						mui.ajax(app.getUrl() + "userinfo/modify", {
							type: 'POST',
							dataType: 'json',
							contentType: "application/json;charset=UTF-8",
							data: regInfo,
							success: function(res) {
								if (res.errCode === "000000") {
									mui.toast('修改成功!', {
										duration: 'long',
										type: 'div'
									})
									mui.ajax(app.getUrl() + "userinfo/getUserInfo", {
										type: 'POST',
										dataType: 'json',
										contentType: "application/json;charset=UTF-8",
										data: {
											"token": user.token
										},
										success: function(res) {
											if (res.errCode === "000000") {
													app.setUserInfo(res.data);
													mui.toast('修改成功!', {
														duration: 'long',
														type: 'div' 
													})
													setTimeout(function(){
														var mainView = plus.webview.getWebviewById("my/my.html");
														mui.fire(mainView, 'reload');
														plus.webview.currentWebview().close();
													},1000);
													
											}
										},
										error: function(res) {
											mui.alert('与服务器断开连接!请重新登录', function() {
												// plus.webview.getWebviewById("index").close();
											});
										}
									});
									  
								}else {
									mui.toast('修改失败!', {
										duration: 'long',
										type: 'div'
									})
								}
							},
							error: function(res) {
								mui.alert('与服务器断开连接!请重新登录', function() {
									// plus.webview.getWebviewById("index").close();
								});
							}
						});
						});
					});
					
					
				
				
				
				
			}(mui, document));
			
			
			});
		</script>
	</body>

</html>